<?php

/**
 * Created by PhpStorm.
 * User: jochen
 * Date: 2017/1/9
 * Time: 上午10:14
 */

use Illuminate\Database\ConnectionResolver;
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Eloquent\Model;

/**
 * 需要进行模型类的CRUD单元测试的，需要继承此类
 * Class ModelTestCase
 */
abstract class ModelTestCase extends PHPUnit_Framework_TestCase
{
    protected $preDestroy = [];

    public function setUp()
    {
        parent::setUp(); // TODO: Change the autogenerated stub
        // 设置默认数据库连接
        $dbConfig = [
            'driver' => 'mongodb',
            'host' => 'dev.eweilink.com',
            'port' => '27017',
            'database' => 'eweilink_test',
            'username' => '',
            'password' => '',
            'options'  => [],
        ];
        $this->createDbByConnectionResolver($dbConfig);
    }

    public function tearDown()
    {
        $this->gc(); // 回收
        parent::tearDown(); // TODO: Change the autogenerated stub
    }

    protected function pluginDatabaseName($defaultConfig)
    {
        $defaultConfig['database'] = \EWeiLink\JuPai\JuPai::plugin_database_name;
        return $defaultConfig;
    }

    protected function createDbByConnectionResolver($dbConfig)
    {
        $resolve = new ConnectionResolver([
            'app' => new Connection($dbConfig),   // 系统默认数据库
            'plugin_jp' => new Connection($this->pluginDatabaseName($dbConfig)),  // 当前插件使用的库
        ]);
        $resolve->setDefaultConnection('app'); // 默认库设为系统自定义的
        Model::setConnectionResolver($resolve);
    }

    protected function preDestroy($someone)
    {
        if (is_array($someone)) {
            array_merge($this->preDestroy, $someone);
        } else {
            array_push($this->preDestroy, $someone);
        }
    }

    protected function gc()
    {
        array_walk($this->preDestroy, function($obj) {
            if (method_exists($obj, 'delete')) {
                $obj->delete();
            }
            else if (method_exists($obj, 'destroy')) {
                $obj->destroy();
            } else {
                $obj = null;
            }
        });
    }
}